package com.hw.sssd.service;

import com.hw.sssd.entity.User;
import com.hw.sssd.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true)
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public Page<User> list(Integer page) {
        Sort.Order order1 = new Sort.Order( Direction.DESC, "id");

        Sort sort = new Sort(order1);

        PageRequest pageRequest = new PageRequest(page, 3, sort);
        Page<User> pageUser = userRepository.findByNameLike( "%2%",pageRequest );

        System.out.println("总记录数: " + pageUser.getTotalElements());
        System.out.println("当前第几页: " + (pageUser.getNumber() + 1));
        System.out.println("总页数: " + pageUser.getTotalPages());
        System.out.println("当前页面的 List: " + pageUser.getContent());
        System.out.println("当前页面的记录数: " + pageUser.getNumberOfElements());
        return userRepository.findByNameLike( "%2%",pageRequest );
    }

    @Transactional
    public User save(User user) {
        return userRepository.save( user );
    }

    @Transactional
    public void update(User user) {
        User one = userRepository.findOne( user.getId() );
        one.setName( user.getName() );
    }
}
